package jude.java.money.batch.task;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jude.java.money.batch.Definition;
import jude.java.money.batch.Keys;
import jude.java.money.batch.Parameter;
import jude.java.money.batch.memory.Sites;
import jude.java.money.batch.task.expand.UpdateCodeTask;
import jude.java.util.FileUtils;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;

/**
 * 批量删除文件
 * */
public class BatchDelete extends BatchTask<String[]> implements UpdateCodeTask {
	
	private static final String CODE =
		"$path = $_POST['path'];\r\n" +
//		"echo $path; "+
		"if(file_exists($path))" +
		"  if(unlink($path))" +
		"    echo \"Success\";\r\n" +
		"  else" +
		"   echo \"Failure\";" +
		"else" +
		"  echo 'not-exists';" +
		"die();";
	
	public BatchDelete(Parameter<String[]> p) {
		super(p);
	}
	
	@Override
	protected String getLabel() {
		return "DEL";
	}
	
	protected void execute(String site, String url, int group, int index) throws IOException {
		HttpClient client = getHttpClient();
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		NameValuePair key = new NameValuePair("key", P.KEY);
		String[] files = P.PARAMS;
		for (int i = 0; i < files.length; i++) {
//			print("\r\n").print(files[i]).print("\t");
			params.clear();
			params.add(key);
			String path = files[i];
			if (P.TYPE == Definition.TYPE_ZENCART && path.contains(Keys.TEMPLATE)) {
				String template = Sites.getTemplateDir(site);
				if (template == null) {
					L.result(i, "template_dir not set");
					continue;
				}
				path = StringUtils.replace(path, Keys.TEMPLATE, template);
			}
			path = FileUtils.normalizePath(path);
//			path = path.replace('\\', '/');
//			if (!path.startsWith("/"))
//				path = "./" + path;
			String code = CODE;
			params.add(new NameValuePair("path", path));
			params.add(new NameValuePair("value", code));
			PostMethod post = getPostMethod(url, params);
			shieldPost(i, site, client, post);
		}
	}
	
	@Override
	protected void createPatch() {
		String[] params = P.PARAMS;
		System.out.println();
		for (int i = 0; i < params.length; i++) {
			String path = params[i].replace('\\', '/');
			System.out.println("unlink('" + path + "');");
		}
		System.out.println();
	}
}
